<template>
  <div class="root">
    <div class="container-shell">
      <div class="container" ref="container"></div>
      <div class="controls">
        <div class="top">
          <span class="txt">音频对讲</span>
          <button v-if="!talkStatus" @click.stop="toBtn">开启</button>
          <button v-else @click.stop="toBtn">关闭</button>
        </div>
        <div class="controls_box">
          <div class="btn" @click="ptzCamera('up')">上</div>
          <div class="content">
            <div class="btn" @click="ptzCamera('left')">左</div>
            <div class="btn" @click="ptzCamera('stop')">停止</div>
            <div class="btn" @click="ptzCamera('right')">右</div>
          </div>
          <div class="btn" @click="ptzCamera('down')">下</div>
          <!-- <div class="btn" @click="toAduio">麦克风-开启</div>
          <div class="btn" @click="toStop">麦克风-关闭</div> -->
        </div>
        <div v-show="false">
          <video ref="video" controls autoplay></video>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "DemoPlayer",
  props: {},
  data() {
    return {
      vdList: [], //视频列表
      jessibuca: null,
      zlmRTCClient: null,
      mediaStream: null, //麦克风
      playing: false,
      quieting: true,
      loaded: false, // mute
      showOperateBtns: true,
      showBandwidth: false,
      err: "",
      speed: 0,
      performance: "1",
      volume: 1,
      rotate: 0,
      useMSE: true,
      useOffscreen: false,
      recording: false,
      talkStatus: false, //语音对讲
      // microphoneStatus: false, //摄像头
      recordType: "webm",
      scale: 0,
      controSpeed: "", //放大倍数
      baseUrl: "https://192.168.2.127:18080/api",
      urlId: "34020000001320000088/34020000001370000001",
    };
  },
  created() {
    
    this.init();
  },
  unmounted() {
    this.jessibuca.destroy();
  },
  methods: {
    // 关闭麦克风
    stoptoMicrophone() {
      if (!this.mediaStream) {
        return;
      }
      this.mediaStream.getAudioTracks().forEach((track) => track.stop());
      this.mediaStream = null;
      console.log("麦克风已关闭！！！");
    },

    // 开启麦克风
    async toMicrophone() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        this.mediaStream = stream;
        console.log("开启麦克风！！！");
      } catch (err) {
        console.log("无法麦克风", err);
      }
    },
    // 点播视频
    init() {
      axios({
        method: "get",
        url:
          "https://192.168.2.127:18080/api/play/start/34020000001320000088/34020000001370000001",
        headers: {
          Accept: "application/json, text/plain, */*",
          "Accept-Encoding": "gzip, deflate, br",
          "Accept-Language": "zh-CN,zh;q=0.9",
          "Access-Token":
            "eyJhbGciOiJSUzI1NiIsImtpZCI6IjNlNzk2NDZjNGRiYzQwODM4M2E5ZWVkMDlmMmI4NWFlIn0.eyJqdGkiOiJidEpVc3pNQzlGQlJObmdSWHlTVzVnIiwiaWF0IjoxNzAyMDIwNjU0LCJleHAiOjE3MDQ2MTI2NTQsIm5iZiI6MTcwMjAyMDY1NCwic3ViIjoibG9naW4iLCJhdWQiOiJBdWRpZW5jZSIsInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjIxMjMyZjI5N2E1N2E1YTc0Mzg5NGEwZTRhODAxZmMzIiwicm9sZUlkIjoxfQ.Tfukfmr9K6lQJWAZzlT2Fl_EqYwq4y4mNychsFiR1A_SYdHtrrZ-nTyZUn8TJMNDpm4nkGfZw_0obIk5jCAXUy-1EvMkY1rjfgpFb8S9hzKy1URA2FdLqQEycvsbXzi8sdedBlw2Vvxl6faTKNBbw9rnuCbe4Nv2-xOUZnRKo6TfZeaybJSVKBYyqxsb6rtDa43Pmq7GDU1_fbFl9WBu58oFSkyoU79hhQ-_3B8i-1bR_catjKLLWPGQxA3yrvUCdqwM0bmtyTu0fcrjhxZX8LXIkLDrNOjkcyKGqLSGXwOBekJBJKhuWYHp39uBmKHEKIOMrJfB8RH-H_-bBpWSyg",
          "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
          Host: "192.168.2.127:18080",
          Connection: "keep-alive",
        },
      }).then((res) => {
        if (res.data.code === 0) {
          let options = {};
          this.create(options, res.data.data.https_flv);
          // console.log("res===", res.data.data );
        }
      });
    },
    // 语音对讲按钮
    toBtn() {
      if (!this.talkStatus && this.canTalk) {
        // 开启麦克风
      this.toMicrophone();
        this.startTalk();
      } else if (this.talkStatus == true) {
        this.stopTalk();
      }
       this.talkStatus = !this.talkStatus;
    },

    // 停止对讲功能
    stopTalk() {
      // 关闭对讲
      this.zlmRTCClient.close();
      // 关闭麦克风
      this.stoptoMicrophone();
    },
    // 开对讲功能
    startTalk() {
      var _that = this;
      axios({
        method: "get",
        url: this.baseUrl + `/talkback/getWebRtcAddr/${this.urlId}`,
        headers: {
          Accept: "application/json, text/plain, */*",
          "Accept-Language": "zh-CN,zh;q=0.9",
          "Access-Token":
            "eyJhbGciOiJSUzI1NiIsImtpZCI6IjNlNzk2NDZjNGRiYzQwODM4M2E5ZWVkMDlmMmI4NWFlIn0.eyJqdGkiOiJMdnBDUG9GQnRCMXExdUNLQ3dpUkhBIiwiaWF0IjoxNzAxOTI5MzM3LCJleHAiOjE3MDQ1MjEzMzcsIm5iZiI6MTcwMTkyOTMzNywic3ViIjoibG9naW4iLCJhdWQiOiJBdWRpZW5jZSIsInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjIxMjMyZjI5N2E1N2E1YTc0Mzg5NGEwZTRhODAxZmMzIiwicm9sZUlkIjoxfQ.WH86wVdLJWo-_TKkiORBRsoQw0RyYKrADOnDtRsmgHjZRoQJ98pYnCzp2YF2YjsUSVVEZgQGlPlHxiOSuZ0ck_JBw710JfjpzQxywjZtzJAxKlDuMYSwsZ3XydVa9-t4H8ce1nElZXRLEbKlZNoWNYxAd4Gea37YQM1Y3rlLCZOniHKULCYbsuexPhCpaOcNh7lKFYC-dub5iWSFF-yZbAjpJlJCttAKIy3xbkh3gm2Dzvn35ZFoLaWVLjCNqb8uRBPUlHV9oR-viV5H-51-mfVgh5vGuHn3uvtqFPY9gh3XpXouSQyMs9SVFWoPdpt2GLHgtgrZhL2KTViLHPmGUA",
          "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
          Host: "192.168.2.127:18080",
          Connection: "keep-alive",
        },
      })
        .then((res) => {
          console.log("对讲===", res);
          let webRtcPushUrl = res.data.data.webRtcPushUrl;
          let app = res.data.data.app;
          let stream = res.data.data.stream;
          //2.拿到webrtc地址先推流
          _that.zlmRTCClient = new window.ZLMRTCClient.Endpoint({
            element: _that.$refs.video, // video 标签
            debug: false, // 是否打印日志
            zlmsdpUrl: webRtcPushUrl, //流地址
            simulcast: false,
            useCamera: false,
            audioEnable: true,
            videoEnable: false,
            recvOnly: false,
            resolution: { w: 0, h: 0 },
            usedatachannel: false,
          });

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,
            function (e) {
              // ICE 协商出错
              console.log("ICE 协商出错", e);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,
            function (e) {
              // offer anwser 交换失败
              console.log("offer anwser 交换失败", e);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM,
            function (s) {
              // 获取到了本地流
              console.log("获取到了本地流", s);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.CAPTURE_STREAM_FAILED,
            function (s) {
              // 获取本地流失败
              console.log("获取本地流失败", s);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,
            function (state) {
              // RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
              console.log("当前状态==>", state);
              if (state === "connected") {
                //推流成功开始下发语音对讲指令
                axios({
                  method: "get",
                  url:
                    _that.baseUrl + `/talkback/start/${_that.urlId}/${app}/${stream}/0`,
                  headers: {
                    Accept: "application/json, text/plain, */*",
                    "Accept-Language": "zh-CN,zh;q=0.9",
                    "Access-Token":
                      "eyJhbGciOiJSUzI1NiIsImtpZCI6IjNlNzk2NDZjNGRiYzQwODM4M2E5ZWVkMDlmMmI4NWFlIn0.eyJqdGkiOiJMdnBDUG9GQnRCMXExdUNLQ3dpUkhBIiwiaWF0IjoxNzAxOTI5MzM3LCJleHAiOjE3MDQ1MjEzMzcsIm5iZiI6MTcwMTkyOTMzNywic3ViIjoibG9naW4iLCJhdWQiOiJBdWRpZW5jZSIsInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjIxMjMyZjI5N2E1N2E1YTc0Mzg5NGEwZTRhODAxZmMzIiwicm9sZUlkIjoxfQ.WH86wVdLJWo-_TKkiORBRsoQw0RyYKrADOnDtRsmgHjZRoQJ98pYnCzp2YF2YjsUSVVEZgQGlPlHxiOSuZ0ck_JBw710JfjpzQxywjZtzJAxKlDuMYSwsZ3XydVa9-t4H8ce1nElZXRLEbKlZNoWNYxAd4Gea37YQM1Y3rlLCZOniHKULCYbsuexPhCpaOcNh7lKFYC-dub5iWSFF-yZbAjpJlJCttAKIy3xbkh3gm2Dzvn35ZFoLaWVLjCNqb8uRBPUlHV9oR-viV5H-51-mfVgh5vGuHn3uvtqFPY9gh3XpXouSQyMs9SVFWoPdpt2GLHgtgrZhL2KTViLHPmGUA",
                    "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
                    Host: "192.168.2.127:18080",
                    Connection: "keep-alive",
                  },
                })
                  .then((res) => {
                    console.log("语音对讲指令下发", res);
                    if (res.data.code != 0) {
                      console.log("有错误！！！");
                      return;
                    } else {
                      console.log("开始对讲");
                    }
                  })
                  .catch((err) => {
                    console.log("对讲指令下发失败", err);
                    _that.stopTalk();
                  });
              } else if (state === "failed") {
                console.log("webrtc推流失败，请检查流媒体配置");
              }
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_OPEN,
            function (event) {
              console.log("rtc datachannel 打开 :", event);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_ERR,
            function (event) {
              console.log("rtc datachannel 错误 :", event);
            }
          );

          _that.zlmRTCClient.on(
            window.ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_CLOSE,
            function (event) {
              console.log("rtc datachannel 关闭 :", event);
            }
          );
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    //浏览器https|http判断
    canTalk() {
      var ishttps = "https:" == document.location.protocol ? true : false;
      console.log("hasAudiohasAudiohasAudiohasAudio:" + this.hasAudio);
      if (!ishttps || !this.hasAudio) {
        this.talkTitle =
          "由于浏览器安全策略本站必须得是https，并且开启通道音频选项才可以对讲";
        return false;
      }
      this.talkTitle = "开始对讲";
      return true;
    },

    // 定时停止
    setStop() {
      setTimeout(() => {
        this.ptzCamera("stop");
      }, 3000);
    },

    // 控制方向
    ptzCamera(command) {
      // console.log("command", command);
      if (command !== "stop") {
        this.setStop();
      }
      axios({
        method: "post",
        url:
          this.baseUrl +
          `/ptz/control/${this.urlId}?command=${command}&horizonSpeed=20&verticalSpeed=20&zoomSpeed=20`,
        headers: {
          Accept: "application/json, text/plain, */*",
          "Accept-Encoding": "gzip,deflate,br",
          "Accept-Language": "zh-CN,zh;q=0.9",
          "Access-Token":
            "eyJhbGciOiJSUzI1NiIsImtpZCI6IjNlNzk2NDZjNGRiYzQwODM4M2E5ZWVkMDlmMmI4NWFlIn0.eyJqdGkiOiJMdnBDUG9GQnRCMXExdUNLQ3dpUkhBIiwiaWF0IjoxNzAxOTI5MzM3LCJleHAiOjE3MDQ1MjEzMzcsIm5iZiI6MTcwMTkyOTMzNywic3ViIjoibG9naW4iLCJhdWQiOiJBdWRpZW5jZSIsInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjIxMjMyZjI5N2E1N2E1YTc0Mzg5NGEwZTRhODAxZmMzIiwicm9sZUlkIjoxfQ.WH86wVdLJWo-_TKkiORBRsoQw0RyYKrADOnDtRsmgHjZRoQJ98pYnCzp2YF2YjsUSVVEZgQGlPlHxiOSuZ0ck_JBw710JfjpzQxywjZtzJAxKlDuMYSwsZ3XydVa9-t4H8ce1nElZXRLEbKlZNoWNYxAd4Gea37YQM1Y3rlLCZOniHKULCYbsuexPhCpaOcNh7lKFYC-dub5iWSFF-yZbAjpJlJCttAKIy3xbkh3gm2Dzvn35ZFoLaWVLjCNqb8uRBPUlHV9oR-viV5H-51-mfVgh5vGuHn3uvtqFPY9gh3XpXouSQyMs9SVFWoPdpt2GLHgtgrZhL2KTViLHPmGUA",
          "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
          Host: "192.168.2.127:18080",
          Connection: "keep-alive",
        },
      }).then((res) => {
        console.log("res===", res);
      });
    },
    // 创建视频事件
    create(options, url) {
      options = options || {};
      this.jessibuca = new window.Jessibuca(
        Object.assign(
          {
            container: this.$refs.container, //视频挂在元素
            videoBuffer: "0.2", // 缓存时长
            isResize: false,
            useMSE: this.useMSE,
            text: "",
            // background: "bg.jpg",
            loadingText: "疯狂加载中...",
            hasAudio: true,
            debug: true,
            supportDblclickFullscreen: true,
            microphoneStatus: this.talkStatus, //语音对讲
            showBandwidth: true, // 显示网速
            operateBtns: {
              fullscreen: this.showOperateBtns,
              screenshot: this.showOperateBtns,
              play: this.showOperateBtns,
              audio: this.showOperateBtns,
            },
            vod: this.vod,
            forceNoOffscreen: !this.useOffscreen,
            isNotMute: false, //静音播放
            timeout: 10,
          },
          options
        )
      );
      var _this = this;

      this.jessibuca.on("performance", function (performance) {
        var show = "卡顿";
        if (performance === 2) {
          show = "非常流畅";
        } else if (performance === 1) {
          show = "流畅";
        }
        _this.performance = show;
      });

      this.jessibuca.on("kBps", function (kBps) {
        if (kBps == 0) {
          // this.jessibuca.play(url);
          this.playing = true;
        }
        // console.log("kBps", kBps);
      });

      this.jessibuca.on("play", () => {
        this.playing = true;
        this.loaded = true;
        this.quieting = this.jessibuca.isMute();
      });
      this.jessibuca.on("pause", () => {
        this.playing = true;
      });
      // 加载播放
      this.jessibuca.play(url);
    },
  },
};
</script>
<style>
.container-shell {
  margin: 0 auto;
  /* width: 1600px; */
  /* height: 800px; */
  display: flex;
  /* flex-wrap: wrap; */
  /* background-color: pink; */
  justify-content: space-around;
  /* background-color: pink; */
}

.container {
  background: rgba(13, 14, 27, 0.7);
  width: 30%;
  height: 350px;
  margin-top: 100px;
}
.controls {
  width: 350px;
  box-sizing: border-box;
  /* background-color: #fff; */
  padding: 20px;
  border: 1px solid #000;
}
.txt {
  margin-right: 20px;
}
.controls_box {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.btn {
  /* width: 50px; */
  text-align: center;
  padding: 8px 25px;
  color: #fff;
  background-color: #0b5499;
  margin: 10px;
  border-radius: 5px;
  cursor: pointer;
}
.content {
  display: flex;
}
</style>
